﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using QuickBencher.Repositories;

namespace QuickBencher
{
    public class HtmlReportPrinter : Printer
    {
		public static string QuickBencherDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "QuickBencher");
        private readonly ConsolePrinter consolePrinter = new ConsolePrinter();

    	public bool DisplayWebPage { get; set; }

		public void Print(object o)
        {
            if (o == null) throw new ArgumentNullException();
            if (o.GetType() != typeof(Measurement)) throw new ArgumentException("Arg must be of type Measurement");

			consolePrinter.Print(o);

			GetMeasurementRepository().Save(o as Measurement);
			CreateHtml();
			CreateStylesheets();
			CreateScripts();

			if (DisplayWebPage)
				ShowWebPage();	
        }

    	protected virtual void ShowWebPage()
    	{
    		Process.Start(HtmlReportFilePath);
    	}

    	private static void CreateScripts()
    	{
    		Directory.CreateDirectory(Path.Combine(QuickBencherDir, "scripts"));
			CopyEmbeddedResourceToDisk("QuickBencher.Internal.HtmlReports.scripts.quickbencher.js", Path.Combine(QuickBencherDir, "scripts\\quickbencher.js"));
			CopyEmbeddedResourceToDisk("QuickBencher.Internal.HtmlReports.scripts.jquery-1.4.2.js", Path.Combine(QuickBencherDir, "scripts\\jquery-1.4.2.js"));
			CopyEmbeddedResourceToDisk("QuickBencher.Internal.HtmlReports.scripts.jquery.flot.js", Path.Combine(QuickBencherDir, "scripts\\jquery.flot.js"));
		}

    	private static void CopyEmbeddedResourceToDisk(string resource, string filePath)
    	{
    		using (var sw = new StreamWriter(filePath))
    		{
    			sw.Write(GetManifestResourceAsString(resource));
    		}
    	}

    	private static void CreateStylesheets()
    	{
    		Directory.CreateDirectory(Path.Combine(QuickBencherDir, "css"));
			CopyEmbeddedResourceToDisk("QuickBencher.Internal.HtmlReports.css.default.css", Path.Combine(QuickBencherDir, "css\\default.css"));
    	}

    	private static void CreateHtml()
    	{
			CopyEmbeddedResourceToDisk("QuickBencher.Internal.HtmlReports.Report.html", HtmlReportFilePath);
    	}

    	private static string GetManifestResourceAsString(string resource)
    	{
    		using (var sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)))
    		{
    			return sr.ReadToEnd();
    		}
    	}

    	private readonly MeasurementRepository _repository = new MeasurementRepository();
    	private static readonly string HtmlReportFilePath = Path.Combine(QuickBencherDir, "Report.html");

    	protected virtual MeasurementRepository GetMeasurementRepository()
		{
			return _repository;
		}
    }
}
